import * as React from "react";
import {
  Button,
  Modal,
  Spin,
  Table,
  Input,
  Row,
  Col,
  Form,
  Radio,
  Space,
} from "antd";
import IconFont from "../../../../../../assets/ICON";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import {
  getConfigDetailByAmiId,
  getProtocalCmd,
  addConfigDetail,
  deleteConfigDetail,
  updateConfigDetail,
} from "../../../ServeApi/index";
import "./index.less";

export interface CollectionMethodSettingProps {
  isModalVisible: boolean;
  record: any | null;
  onCancel: () => any;
}

export interface CollectionMethodSettingState {
  loading: boolean;
}

class CollectionMethodSetting extends React.Component<
  CollectionMethodSettingProps,
  CollectionMethodSettingState
> {
  state = { loading: false };
  private initValue: any = null;
  private pageIndex: number = 1;
  private pageSize: number = 5;
  private total: number = 0;
  private dataSouce: any[] = [];
  private ProtocalData: any[] = [];
  private instance: any = null;
  activeKey = "1";
  shujuleixidiyige: string = "";
  bound: number = 1;
  private columns: columnsDataCLass[] = [
    {
      title: "数据类型",
      dataIndex: "commandName",
      key: "commandName",
    },
    {
      title: "数据密度",
      dataIndex: "dataDensity",
      key: "dataDensity",
      render: (text, record) => {
        let str = "分钟";
        switch (record.dataDensityType) {
          case 1:
            str = "分钟";
            break;
          case 2:
            str = "小时";
            break;
          case 3:
            str = "日";
            break;
          case 4:
            str = "月";
            break;
          default:
            break;
        }
        return text + str;
      },
    },
    {
      title: "采集密度",
      dataIndex: "collectionDensity",
      key: "collectionDensity",
      render: (text, record) => {
        let str = "分钟";
        switch (record.collectionDensityType) {
          case 1:
            str = "分钟";
            break;
          case 2:
            str = "小时";
            break;
          case 3:
            str = "日";
            break;
          case 4:
            str = "月";
            break;
          default:
            break;
        }
        return text + str;
      },
    },
    {
      title: "开始时分",
      dataIndex: "startHourMin",
      key: "startHourMin",
    },
    {
      title: "编辑/删除",
      dataIndex: "action",
      key: "action",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  // this.Mod = "updata";
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
              </span>

              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onDelete(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
              </span>
            </Space>
          </>
        );
      },
    },
  ];

  render() {
    let { isModalVisible } = this.props;
    return (
      <>
        <Modal
          className="CollectionMethodSetting"
          title={"命令配置:" + this.props.record?.name}
          visible={isModalVisible}
          okText="添加"
          okType="ghost"
          onCancel={() => {
            // this.handleFeedCancel();
            this.props.onCancel();
          }}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.initFromData();
              }}
            >
              重置
            </Button>,
            <Button
              key="back"
              onClick={() => {
                this.onSumbit();
              }}
              type="primary"
            >
              保存
            </Button>,
          ]}
        >
          <Spin spinning={this.state.loading}>
            <Table
              size="small"
              columns={this.columns}
              dataSource={this.dataSouce}
              pagination={{
                pageSize: this.pageSize,
                total: this.total,
                onChange: (page: number) => {
                  this.pageIndex = page;
                  this.setPream();
                },
              }}
            ></Table>
          </Spin>
          <div className="Tab">
            <text
              className={this.activeKey === "1" ? "action" : ""}
              onClick={() => {
                this.activeKey = "1";
                this.forceUpdate();
                this.initFromData();
              }}
            >
              新增命令
            </text>
            <text className={this.activeKey === "2" ? "action" : "disable"}>
              编辑命令
            </text>
          </div>
          <Form ref={(el) => (this.instance = el)}>
            <Row>
              <Col span={24}>
                <Form.Item
                  label="数据类型："
                  name="commandKey"
                  rules={[
                    {
                      required: true,
                      message: "数据类型必填",
                    },
                  ]}
                >
                  <Radio.Group>
                    {this.ProtocalData.map((item: any, index: number) => {
                      return <Radio value={item.commandKey}>{item.name}</Radio>;
                    })}
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Row>
                  <Col span={18}>
                    <Form.Item
                      label="数据密度："
                      name="dataDensityType"
                      rules={[
                        {
                          required: true,
                          message: "数据密度必填",
                        },
                      ]}
                    >
                      <Radio.Group>
                        <Radio value={1}>分钟</Radio>
                        <Radio value={2}>小时</Radio>
                        <Radio value={3}>日</Radio>
                        <Radio value={4}>月</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      name="dataDensity"
                      rules={[
                        {
                          required: true,
                          pattern: new RegExp(/^[1-9]\d*$/, "g"),
                          message: "请输入正确数值!",
                        },
                      ]}
                    >
                      <Input placeholder="数据密度" />
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col span={24}>
                <Row>
                  <Col span={18}>
                    <Form.Item
                      label="采集密度："
                      name="collectionDensityType"
                      rules={[{ required: true, message: "请输入正确数值!" }]}
                    >
                      <Radio.Group>
                        <Radio value={1}>分钟</Radio>
                        <Radio value={2}>小时</Radio>
                        <Radio value={3}>日</Radio>
                        <Radio value={4}>月</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      name="collectionDensity"
                      rules={[
                        {
                          required: true,
                          pattern: new RegExp(/^[1-9]\d*$/, "g"),
                          message: "请输入正确数值!",
                        },
                      ]}
                    >
                      <Input placeholder="采集密度" />
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="开始时分："
                  name="startHourMin"
                  rules={[
                    {
                      required: true,
                      pattern: new RegExp(
                        /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$/,
                        "g"
                      ),
                      message: "请输入正确时间!",
                    },
                  ]}
                >
                  <Input placeholder="HH:mm" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </>
    );
  }
  componentWillMount() {
    this.getProtocalCmd();
  }
  componentDidMount() {
    this.init();
  }
  init() {
    this.setPream();
    this.initFromData();
  }
  /**主动触发 */
  //编辑配置命令触发
  onEdit(record) {
    this.initValue = record;
    this.activeKey = "2";
    this.forceUpdate();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(record);
      }
    });
  }
  //删除配置命令触发
  onDelete(item) {
    let pream = {
      id: item.id,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除配置命令",
      onOk: () => {
        _this.deleteConfigDetail(pream);
      },
    });
  }
  //初始化表单重置
  initFromData() {
    this.initValue = null;
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue({
          dataDensityType: 1,
          collectionDensityType: 1,
          commandKey: undefined,
          dataDensity: undefined,
          collectionDensity: undefined,
          startHourMin: undefined,
        });
      }
    });
  }

  getProtocalDataValue(commandKey) {
    let str = "";
    this.ProtocalData.map((item) => {
      if (commandKey === item.commandKey) {
        str = item.name;
      }
      return item;
    });
    return str;
  }
  //保存
  onSumbit() {
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        console.log(res);
        _this.addOrEditSubmitSetPream(res);
        // _
      })
      .catch((err) => {
        console.log(err);
      });
  }
  addOrEditSubmitSetPream(item) {
    let { record } = this.props;
    item.commandName = this.getProtocalDataValue(item.commandKey);
    item.collectionId = record.id;

    switch (this.activeKey) {
      case "1":
        //新增命令
        this.addConfigDetail(item);
        break;
      case "2":
        item.id = this.initValue["id"];
        this.updateConfigDetail(item);
        //编辑命令
        break;
      default:
        break;
    }
  }
  setPream() {
    let { record } = this.props;
    let pream = {
      amiId: record.id,
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
    };
    this.getList(pream);
  }
  //获取配置明细分页查询
  async getList(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await getConfigDetailByAmiId(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataSouce = json.data.records;
        _this.total = json.data.total;
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //获取配置数据类型
  async getProtocalCmd() {
    let _this = this;
    this.setState({ loading: true });
    let { record } = this.props;
    let pream = {
      protocalTypeId: record.protocalTypeId,
    };
    try {
      let res: any = await getProtocalCmd(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.ProtocalData = json.data;
        _this.shujuleixidiyige = json.data[0].commandKey;
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //新增配置命令
  async addConfigDetail(pream) {
    let _this = this;
    this.setState({ loading: true });

    try {
      let res: any = await addConfigDetail(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.setPream();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //编辑配置命令
  async updateConfigDetail(pream) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await updateConfigDetail(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.setPream();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  async deleteConfigDetail(pream) {
    let _this = this;
    this.setState({ loading: true });

    try {
      let res: any = await deleteConfigDetail(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.setPream();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default CollectionMethodSetting;
